package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func InsertUserBackpackBatchesData(session *gorm.DB, data []*models_main.UserBackpack) error {
	fName := "InsertData"
	err := session.Model(&data).CreateInBatches(data, global2.BatchSize).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func GetUserBackpacksParam(param map[string]interface{}, order string, page, size int) ([]*models_main.UserBackpack, error) {
	fName := "GetPartUsersParam"
	o := make([]*models_main.UserBackpack, 0)
	table := mysql.GetRTable(&models_main.UserBackpack{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetBackpackParam(param map[string]interface{}) ([]*models_main.UserBackpack, error) {
	fName := "GetBackpackParam"
	o := []*models_main.UserBackpack{}
	table := mysql.GetXTable(&models_main.UserBackpack{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

/**
 * @Author willi
 * @Description //TODO
 * @Date 10:21 2022/9/7
 * @Param
 * @return
 **/
func CountBackpackParam(uid, gid int) int64 {
	var quantity int64
	global2.GetR().Raw("select quantity-used_quantity quantity  from db_user_backpack_statistics where uid=? and gid=? and quantity-used_quantity>0 ", uid, gid).Scan(&quantity)
	return quantity
}

/**
 * @Author
 * @Description //TODO
 * @Date 10:46 2022/9/7
 * @Param
 * @return
 **/
func UseProps(session *gorm.DB, uid, gid, category, count int) bool {
	rowsAffected := session.Exec("update db_user_backpack_statistics set used_quantity=used_quantity+? where uid=? and gid=? and type=? and quantity>=used_quantity+?", count, uid, gid, category, count).RowsAffected
	if rowsAffected > 0 {
		return true
	} else {
		return false
	}
}

func UpdateUserBackpack(uid int) error {
	fName := "InsertData"
	err := mysql.GetXTable(&models_main.UserBackpack{}).Where("type = 2").Where("uid = ? ", uid).Update("selected", 0).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
